<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.title"
        placeholder="请输入轮播图标题"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-model="listQuery.status"
        placeholder="状态"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option 
          v-for="item in statusOptions" 
          :key="item.value" 
          :label="item.label" 
          :value="item.value" 
        />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        添加
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="正在加载..."
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="ID" align="center" width="80px">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="标题" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="图片" width="180px" align="center">
        <template slot-scope="scope">
          <div class="image-container">
            <img 
              v-if="scope.row.imageUrl" 
              :src="formatImageUrl(scope.row.imageUrl)" 
              class="carousel-image"
              @click="previewImage(scope.row.imageUrl)">
            <div v-else class="no-image">
              <i class="el-icon-picture-outline"></i>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="跳转链接" min-width="150px">
        <template slot-scope="scope">
          <span>{{ scope.row.linkUrl || '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="顺序" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.sequence }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" width="100px" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleUpdate(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="listQuery.pageNum"
        :page-sizes="[5, 10, 20, 30, 50]"
        :page-size="listQuery.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 编辑/添加对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="轮播图标题" prop="title">
          <el-input v-model="temp.title" placeholder="请输入轮播图标题" />
        </el-form-item>
        <el-form-item label="轮播图图片" prop="imageUrl">
          <el-upload
            class="carousel-uploader"
            action="#"
            :http-request="handleImageUpload"
            :show-file-list="false"
            :before-upload="beforeImageUpload"
          >
            <img v-if="temp.imageUrl" :src="formatImageUrl(temp.imageUrl)" class="carousel-upload-image">
            <i v-else class="el-icon-plus carousel-uploader-icon"></i>
          </el-upload>
          <div v-if="temp.imageUrl" class="el-upload__tip">
            <span>图片URL: {{ temp.imageUrl }}</span>
          </div>
          <div class="el-upload__tip">只能上传jpg/png文件，且不超过5MB</div>
        </el-form-item>
        <el-form-item label="跳转链接">
          <el-input v-model="temp.linkUrl" placeholder="请输入跳转链接（可选）"/>
        </el-form-item>
        <el-form-item label="显示顺序" prop="sequence">
          <el-input-number v-model="temp.sequence" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="temp.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="dialogStatus === 'create' ? createData() : updateData()"
        >
          确认
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  pageCarousel, 
  getCarouselDetail, 
  addCarousel, 
  updateCarousel, 
  deleteCarousel, 
  updateCarouselStatus 
} from '@/api/modules/app/carouselApi'
import { uploadImage } from '@/api/modules/app/uploadApi'

export default {
  name: 'CarouselManagement',
  data() {
    return {
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        title: '',
        status: undefined
      },
      statusOptions: [
        { label: '启用', value: 1 },
        { label: '禁用', value: 0 }
      ],
      temp: {
        id: undefined,
        title: '',
        imageUrl: '',
        linkUrl: '',
        sequence: 0,
        status: 1
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑轮播图',
        create: '添加轮播图'
      },
      rules: {
        title: [{ required: true, message: '轮播图标题不能为空', trigger: 'blur' }],
        imageUrl: [{ required: true, message: '图片地址不能为空', trigger: 'blur' }],
        sequence: [{ required: true, message: '显示顺序不能为空', trigger: 'blur' }]
      },
      imageBaseUrl: 'http://localhost:9101', // 图片基础URL - 只包含IP和端口
      uploadLoading: false
    }
  },
  created() {
    this.getList()
    // 适配不同环境的图片基础URL
    if (process.env.NODE_ENV === 'production') {
      // 生产环境可能使用其他域名
      this.imageBaseUrl = 'https://xxl.today' 
    }
  },
  methods: {
    getList() {
      this.listLoading = true
      pageCarousel(this.listQuery).then(response => {
        if (response.code === 200) {
          this.list = response.data.list
          this.total = response.data.total
        }
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        imageUrl: '',
        linkUrl: '',
        sequence: 0,
        status: 1
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addCarousel(this.temp).then(response => {
            if (response.code === 200) {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            } else {
              this.$message.error(response.message || '添加失败')
            }
          })
        }
      })
    },
    handleUpdate(row) {
      getCarouselDetail(row.id).then(response => {
        if (response.code === 200) {
          this.temp = Object.assign({}, response.data)
          this.dialogStatus = 'update'
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['dataForm'].clearValidate()
          })
        } else {
          this.$message.error(response.message || '获取轮播图详情失败')
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateCarousel(tempData).then(response => {
            if (response.code === 200) {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
              this.getList()
            } else {
              this.$message.error(response.message || '更新失败')
            }
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该轮播图吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCarousel(row.id).then(response => {
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          } else {
            this.$message.error(response.message || '删除失败')
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })          
      })
    },
    handleStatusChange(row) {
      updateCarouselStatus(row.id, row.status).then(response => {
        if (response.code === 200) {
          this.$message({
            message: '状态已更新',
            type: 'success'
          })
        } else {
          // 如果更新失败，恢复原来的状态
          row.status = row.status === 1 ? 0 : 1
          this.$message.error(response.message || '状态更新失败')
        }
      })
    },
    formatImageUrl(url) {
      if (!url) return '';
      if (url.startsWith('http')) {
        return url;
      } else {
        // 将后端返回的相对路径拼接成完整的URL
        // 格式为: baseUrl + /static/image/ + imagePath
        return this.imageBaseUrl + '/tea-admin-api/static/image/' + url;
      }
    },
    handleImageUpload(options) {
      this.uploadLoading = true;
      const formData = new FormData();
      formData.append('file', options.file);
      
      uploadImage(formData).then(response => {
        this.uploadLoading = false;
        if (response.code === 200) {
          this.temp.imageUrl = response.data;
          this.$message.success('图片上传成功');
        } else {
          this.$message.error(response.message || '图片上传失败');
        }
      }).catch(error => {
        this.uploadLoading = false;
        console.error('上传出错', error);
        this.$message.error('图片上传失败');
      });
    },
    beforeImageUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!');
      }
      return isJPG && isLt5M;
    },
    // 预览图片
    previewImage(url) {
      if (!url) return;
      // 使用Element UI的图片预览功能
      const h = this.$createElement;
      this.$msgbox({
        title: '图片预览',
        message: h('div', { class: 'image-preview-dialog' }, [
          h('img', {
            attrs: {
              src: this.formatImageUrl(url),
              alt: '轮播图',
            },
            style: {
              width: '100%',
              maxHeight: '500px',
              objectFit: 'contain'
            }
          })
        ]),
        showCancelButton: false,
        confirmButtonText: '关闭'
      }).catch(() => {});
    }
  }
}
</script>

<style scoped>
.filter-container {
  padding-bottom: 10px;
}
.filter-item {
  margin-right: 10px;
}
.pagination-container {
  padding: 32px 16px;
}
.image-container {
  width: 100px;
  height: 60px;
  margin: 0 auto;
  overflow: hidden;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  position: relative;
}
.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  cursor: pointer;
}
.no-image {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
}
.carousel-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.carousel-uploader:hover {
  border-color: #409EFF;
}
.carousel-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.carousel-upload-image {
  width: 178px;
  height: 178px;
  display: block;
}
.image-preview-dialog img {
  width: 100%;
  display: block;
}
</style>  